#include <iostream>
#include <string>
#include <strings.h>
#include <cstring>
#include <pthread.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Terminal.hpp"

#define BUFF_SIZE 1024

void usage(const char *str)
{
    std::cout << "usage: \n\t";
    std::cout << str << " server_ip server_port" << std::endl;
}

struct ThreadData
{
    struct sockaddr_in server;
    int sockfd;
};

void *ReceiveMessage(void *args)
{
    Redirect();
    ThreadData *td = static_cast<ThreadData *>(args);
    char buff[BUFF_SIZE];
    while (true)
    {
        struct sockaddr_in tmp;
        socklen_t len = sizeof(tmp);
        ssize_t sz = recvfrom(td->sockfd, buff, BUFF_SIZE - 1, 0, (sockaddr *)&tmp, &len);
        if (sz > 0)
        {
            buff[sz] = 0;
            // std::cout << "[" << inet_ntoa(td->server.sin_addr) << ":" << std::to_string(ntohs(td->server.sin_port)) << "]:" << buff << std::endl;
            std::cerr << "[" << inet_ntoa(td->server.sin_addr) << ":" << std::to_string(ntohs(td->server.sin_port)) << "]:" << buff << std::endl;
        }
    }
}

void *SendMessage(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    std::string come = "[";
    come += inet_ntoa(td->server.sin_addr);
    come += ":";
    come += std::to_string(ntohs(td->server.sin_port));
    come += "]coming";

    sendto(td->sockfd, come.c_str(), come.size(), 0, (sockaddr *)&(td->server), sizeof(td->server));
    std::string message;
    while (true)
    {
        std::cout << "Enter your message: ";
        std::getline(std::cin, message);
        sendto(td->sockfd, message.c_str(), message.size(), 0, (sockaddr *)&(td->server), sizeof(td->server));
    }
}

// ./client server_ip server_port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        usage(argv[0]);

        // return 0;
        exit(0); // 不是预期的结果。可以用exit退出
    }

    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    // int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    // if (sockfd < 0)
    // {
    //     // 因为本程序只有一个地方会有错误，则可以直接输出错误消息而不用Log
    //     std::cout << "clinet socker error" << std::endl;
    // }

    // struct sockaddr_in server;
    // bzero(&server, sizeof(server));
    // server.sin_family = AF_INET;
    // server.sin_port = htons(server_port);
    // server.sin_addr.s_addr = inet_addr(server_ip.c_str());
    // socklen_t len = sizeof(server);

    // // client端不需要自己bind，由OS自由随机选择，在首次发送数据的时候OS进行bind操作

    // // bind(sockfd, (sockaddr *)&server, len);

    // std::string message;
    // // std::string receive_message;
    // char buff[BUFF_SIZE];

    // while (true)
    // {
    //     std::cout << "enter message:>";
    //     std::getline(std::cin, message);
    //     sendto(sockfd, message.c_str(), message.size(), 0, (sockaddr *)&server, len);

    //     struct sockaddr_in tmp;
    //     socklen_t tmp_len = sizeof(server);

    //     // 大小需为buff大小减一，因为最后一个位置要预备给\0
    //     ssize_t n = recvfrom(sockfd, buff, BUFF_SIZE - 1, 0, (sockaddr *)&tmp, &tmp_len);
    //     if (n > 0) // 大于零，即有数据才输出
    //     {
    //         buff[n] = 0;
    //         std::cout << "client get a message: " << buff << std::endl;
    //     }
    // }

    // close(sockfd);

    ThreadData td;
    td.sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (td.sockfd < 0)
    {
        std::cout << "clinet socker error" << std::endl;
        return 1;
    }

    bzero(&td.server, sizeof(td.server));
    td.server.sin_family = AF_INET;
    td.server.sin_port = htons(server_port);
    td.server.sin_addr.s_addr = inet_addr(server_ip.c_str());
    socklen_t len = sizeof(td.server);

    pthread_t receiver, sender;
    pthread_create(&receiver, nullptr, ReceiveMessage, &td);
    pthread_create(&sender, nullptr, SendMessage, &td);

    pthread_join(receiver, nullptr);
    pthread_join(sender, nullptr);

    close(td.sockfd); // 最后记得关闭

    return 0;
}